package com.alu4r.atcrowdfunding.util;

import com.alu4r.atcrowdfunding.bean.Permission;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class PermissionTree {

    //根据全部的permission返回一个list树
    public static List<Permission> getTree(List<Permission> allPermission){
        List<Permission> root = new ArrayList<>();
        Map<Integer, Permission> map = new HashMap<>();
        for (Permission permission : allPermission) {
            map.put(permission.getId(),permission);
        }
        for (Permission permission : allPermission) {
            if(permission.getPid() == null){
                root.add(permission);
            }
            if(map.get(permission.getPid()) != null){
                Permission child = map.get(permission.getPid());
                child.getChildren().add(permission);
            }
        }
        return root;
    }
    public static List<Permission> getCheckedTree(List<Permission> allPermission, List<Integer> checkedPermissionId){
        List<Permission> root = new ArrayList<>();
        Map<Integer, Permission> map = new HashMap<>();
        for (Permission permission : allPermission) {
            if(checkedPermissionId.contains(permission.getId())){
                permission.setChecked(true);
            }
            map.put(permission.getId(),permission);

        }
        for (Permission permission : allPermission) {
            if(permission.getPid() == null){
                root.add(permission);
            }
            if(map.get(permission.getPid()) != null){
                Permission child = map.get(permission.getPid());
                child.getChildren().add(permission);
            }
        }
        return root;
    }

}
